<template>
  <div style="height: auto;padding: 20px 0">
    <a-spin :spinning="loading">
      <div v-if="!loading && chartEmpty">
        <!-- 图表上部控制按钮 -->
        <a-row v-if="isUpCol" class="peport-nva" type="flex" justify="space-between">
          <a-col
            :class="['pep-nav-col',{'pep-nav-col-select': index === pepNavColSelect }]"
            :xs="11"
            :sm="11"
            :md="11"
            :lg="4"
            :xl="4"
            v-for="(item,index) in pepNavCols"
            :key="index"
            @click="handleColClick(index)"
          >{{ item }}</a-col>
        </a-row>

        <!-- 图表 -->
        <div style="min-height: 500px;overflow: auto">
          <chart
            v-if="flay"
            ref="chart1"
            :options="orgOptions"
            :auto-resize="true"
            style="min-width:950px;width: 100%;"
          ></chart>
        </div>

        <!-- 按钮控制图表 下部 -->
        <div>
          <a-row class="peport-nva" type="flex" justify="space-between">
            <a-col
              v-for="(item, index) in pePortNvaLists"
              :key="index"
              :xs="10"
              :sm="10"
              :md="10"
              :lg="3"
              :xl="3"
              @click="handleClick(index, item)"
            >
              <div
                :class="['js-new_tabs', {'opp-bag-color':index%2 !== 0}, {'active': index === activeColor}]"
              >
                <a-icon type="caret-up" v-show="index === activeColor" class="inon-up" />
                <p class="item-nav-name">{{item.name}}</p>
                <span>{{item.value}}</span>
              </div>
            </a-col>
          </a-row>
        </div>
      </div>
    </a-spin>

    <div v-show="!loading && !chartEmpty">
      <a-empty
        image="https://gw.alipayobjects.com/mdn/miniapp_social/afts/img/A*pevERLJC9v0AAAAAAAAAAABjAQAAAQ/original"
      >
        <span slot="description">{{$t('pro.reports.notReportsData')}}</span>
        <router-link to="/bidder/editcampaign">
          <a-button type="primary" icon="plus">{{$t('pro.Editcampaigns.CreateCampaign')}}</a-button>
        </router-link>
      </a-empty>
    </div>
  </div>
</template>

<script>
import { parseTime } from "../../../utils/time";
import { getReport } from "../../../api/sys-user-controller";
import { getReportChart } from "../../../api/index";

export default {
  name: "eCharts",
  data() {
    return {
      pepNavCols: ["Total", "User", "Campaign", "Creative"],
      pepNavColSelect: 0,

      activeColor: 0, //默认选中第一个
      charts: {},
      pePortNvaLists: [],
      chartEmpty: true,
      loading: false,

      type: "",
      bottomType: "bids",
      adminServeList: [],
      flay: true
    };
  },
  computed: {
    pePortNvaList() {
      this.pePortNvaLists = this.$t("pro.reports.pePortNvaList");
      return this.pePortNvaLists;
    },
    locale() {
      return this.$store.state.locale;
    }
  },
  methods: {
    //上部选项卡 单击选择
    handleColClick(index) {
      this.pepNavColSelect = index; //选择项
      switch (index) {
        case 0:
          this.type = ""; //表示所有
          break;
        case 1:
          this.type = "user";
          break;
        case 2:
          this.type = "campaigns";
          break;
        case 3:
          this.type = "creative";
          break;
      }

      this.adminFetch();
    },

    //下部选项卡 单击选择
    handleClick(index, item) {
      this.activeColor = index;
      this.bottomType = item.key;
      this.switchTitle(item.key);
    },

    //抓取数据重新图表渲染 222
    switchTitle(title) {
      if (!this.isAdmin) {
        this.orgOptions.series[0].data = this.charts[title];
      } else {
        this.orgOptions.series = this.publicChartsList();
      }
    },

    //普通图表查询
    fetch() {
      let { type, id } = this.$route.params;

      let params = { ...this.dateStage };

      if (type != "index") {
        params.type = type;
      }
      if (id != 0) {
        params.id = id;
      }
      getReportChart(params)
        .then(res => {
          this.loading = false;
          let { data, code } = res.data;

          if (code == "200" && data.length > 0) {
            this.chartEmpty = true;
            let list = data;
            let dateList = []; //X轴日期;

            //统计数据集合
            let serveObj = {
              bids: [],
              pixels: [],
              wins: [],
              winsPrice: [],
              bidsSum: 0,
              pixelsSum: 0,
              winsSum: 0,
              winsPriceSum: 0
            };

            //把所有日期抽取出来
            dateList = list.map(item => {
              serveObj.bids.push(item.bids);
              serveObj.pixels.push(item.pixels);
              serveObj.wins.push(item.wins);
              serveObj.winsPrice.push(item.winsPrice);

              serveObj.bidsSum += item.bids || 0;
              serveObj.pixelsSum += item.pixels || 0;
              serveObj.winsSum += item.wins || 0;
              serveObj.winsPriceSum += item.winsPrice || 0;

              return parseTime(item.dateStats, "{y}-{m}-{d}");
            });

            //x轴 日期
            this.orgOptions.xAxis.data = dateList;
            //把图表所有需要展示的按对象数组存放
            this.charts = serveObj;

            //计算总数
            this.computeNavList(serveObj);

            //默认展示第一个 222
            this.switchTitle("bids");
          } else {
            this.chartEmpty = false;
          }
        })
        .catch(() => {
          this.chartEmpty = false;
          this.loading = false;
        });
    },

    //管理员总图表查询
    adminFetch() {
      this.flay = false;
      let params = { ...this.dateStage };
      params.type = this.type;
      getReport(params)
        .then(res => {
          let { code, data } = res.data;
          this.adminServeList = [];

          //统计数据集合
          let serveObj = {
            bidsSum: 0,
            pixelsSum: 0,
            winsSum: 0,
            winsPriceSum: 0
          };

          if (code == "200" && data.length > 0) {
            this.$emit("getTable", data);
            this.chartEmpty = true;

            let list = data;
            let xDate = [];
            let serveList = [];

            let setMap = new Map();
            list.forEach(item => {
              let userId = item.creativeId || item.campaignsId || item.userId;

              let pixels = item.pixels;
              let bids = item.bids;
              let wins = item.wins;
              let winsPrice = item.winsPrice;

              let getObj = setMap.get();
              // 判断是否存在key
              if (getObj == undefined) {
                let obj = {};

                if (this.type == "user") {
                  obj.name = `${item.firstName || ""} ${item.lastName || ""}`;
                }
                if (this.type == "campaigns") {
                  obj.name = item.campaignsName || "";
                }
                if (this.type == "creative") {
                  console.log(item);
                  obj.name = `${item.creativeName || ""} ${item.campaignsName ||
                    ""}`;
                }

                obj.wins = [];
                obj.pixels = [];
                obj.bids = [];
                obj.winsPrice = [];

                obj.wins.push(wins);
                obj.pixels.push(pixels);
                obj.bids.push(bids);
                obj.winsPrice.push(winsPrice);

                //计算总数
                serveObj.bidsSum += bids;
                serveObj.pixelsSum += pixels;
                serveObj.winsSum += wins;
                serveObj.winsPriceSum += winsPrice;

                // 将时间作为key
                setMap.set(userId, obj);
                serveList.push(obj);
              } else {
                getObj.wins.push(wins);
                getObj.pixels.push(pixels);
                getObj.bids.push(bids);
                getObj.winsPrice.push(winsPrice);

                //计算总数
                serveObj.bidsSum += bids;
                serveObj.pixelsSum += pixels;
                serveObj.winsSum += wins;
                serveObj.winsPriceSum += winsPrice;
              }

              xDate.push(parseTime(item.dateStats, "{y}-{m}-{d}"));
            });

            this.adminServeList = serveList;

            //计算选项总数
            this.computeNavList(serveObj);

            //日期
            this.orgOptions.xAxis.data = Array.from(new Set([...xDate]));
            this.orgOptions.series = this.publicChartsList();
            this.flay = true;
          } else {
            this.chartEmpty = false;
          }
        })
        .catch(() => {
          this.chartEmpty = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    //图表顶部按钮选择 数据处理筛选
    publicChartsList() {
      let list = [];
      list = this.adminServeList.map(item => {
        let charts = {};
        charts.name = item.name || this.bottomType;
        charts.type = "line";
        charts.data = item[this.bottomType] || [];
        return charts;
      });
      return list;
    },

    //根据接口请求数据处理后 动态给图表选项字段计算总数
    computeNavList(serveObj) {
      //给图表下按钮动态加 总数
      this.pePortNvaLists = this.pePortNvaList.map(item => {
        if (item.key == "bids") {
          item.value = `${serveObj.bidsSum}`;
        }
        if (item.key == "pixels") {
          item.value = `${serveObj.pixelsSum}`;
        }
        if (item.key == "wins") {
          item.value = `${serveObj.winsSum}`;
        }
        if (item.key == "winsPrice") {
          item.value = `$${Math.floor(serveObj.winsPriceSum * 100) / 100}`;
        }
        return item;
      });
    },

    init() {
      this.loading = true;
      if (!this.isAdmin) {
        this.fetch();
      } else {
        this.adminFetch();
      }
    },

    resize() {
      let char = this.$refs.chart1;
      if (char) {
        char.resize();
      }
    }
  },
  props: {
    orgOptions: {
      type: Object,
      required: false,
      default: function() {
        return {
          xAxis: {
            //boundaryGap: false,
            type: "category",
            //x轴上的天数
            data: [],
            axisLine: {
              lineStyle: {
                color: this.$store.getters.switchBackColor
              }
            }
          },
          yAxis: {
            type: "value",
            axisLabel: {
              formatter: "{value}"
            },
            axisLine: {
              lineStyle: {
                color: this.$store.getters.switchBackColor
              }
            }
          },
          tooltip: {
            trigger: "axis",
            confine: false
          },
          grid: {
            left: "5%",
            right: "2%",
            top: "10%",
            bottom: "10%"
          },
          //默认只要一条线
          series: [
            {
              data: [],
              type: "line"
            }
          ]
        };
      }
    },
    isUpCol: {
      type: Boolean,
      default: false
    },
    dateStage: {
      type: Object,
      required: false
    },
    isAdmin: {
      type: Boolean,
      default: false
    }
  },

  watch: {
    "dateStage.time"() {
      this.init();
    },
    locale() {
      this.init();
    }
  },

  mounted() {
    this.init();
    this.$nextTick(() => {
      window.addEventListener("resize", this.resize);
    });
  },

  destroyed() {
    this.pePortNvaLists = [];
    window.removeEventListener("resize", this.resize);
  }
};
</script>

<style scoped lang="less">
/*图表功能选项区*/
.peport-nva {
  .pep-nav-col {
    cursor: pointer;
    padding: 5px;
    margin: 15px 0px 10px 0;
    font-size: 1.5rem;
    text-align: center;
    overflow: hidden;
    background-color: #f0f0f0;
  }
  .pep-nav-col-select {
    background-color: @primary-color !important;
    color: #fff;
  }
  .js-new_tabs {
    color: #000;
    background-color: #f0f0f0;
    border-radius: 5px;
    text-decoration: none;
    text-align: center;
    padding: 10px 10px;
    position: relative;
    margin-top: 10px;
    cursor: pointer;
    overflow: hidden;
    .item-nav-name {
      font-size: 1.32em;
    }
    .inon-up {
      position: absolute;
      left: 0;
      right: 0;
      top: -12.2rem;
      margin: auto;
      font-size: 4.5rem;
      color: darkgoldenrod;
      z-index: 99999;
    }
    span {
      font-size: 1.7rem;
      line-height: 32px;
    }
  }
  .opp-bag-color {
    background-color: #e6ffff !important;
  }
  .active {
    background-color: @primary-color !important;
    color: RGB(255, 255, 255) !important;
  }
}
</style>
